package com.starry.push.netty.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.starry.push.netty.domain.LogWsConnect;
import com.starry.push.netty.vo.WsResponse;
import com.starry.push.netty.websocket.WebSocketHandler;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author WuChao
 * @version 1.0
 * @date 2020/11/9 16:36
 */
@Service
public class HandleImpl {

    @Autowired
    private LogWsConnectService logWsConnectService;

    @Transactional
    public void moveContents() {
        List<LogWsConnect> wsConnects = logWsConnectService.list(new QueryWrapper<LogWsConnect>()
                .eq(LogWsConnect.COL_STATUS, 0)
        );


        if (CollectionUtil.isNotEmpty(wsConnects)) {

            List<LogWsConnect> connects = wsConnects.stream().filter(logWsConnect -> {

                LocalDateTime createTime = logWsConnect.getCreateTime();
                Duration duration = Duration.between(createTime, LocalDateTime.now());
                long minutes = duration.toMinutes();
                if (minutes >= 2) {
                    return true;
                }
                return false;
            }).collect(Collectors.toList());

            for (LogWsConnect wsConnect : connects) {
                wsConnect.setStatus(3);
                Channel channel = WebSocketHandler.onlineGroup.get(wsConnect.getChannelId());
                channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(WsResponse.error("长时间未认证,断开链接"))));
                channel.close();
                WebSocketHandler.onlineGroup.remove(wsConnect.getChannelId());
            }

//            logWsConnectService.updateBatch(wsConnects);
        }

    }





}
